package com.wyh.book.interceptor;

import com.wyh.book.enums.StringConstant;
import com.wyh.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王圆豪
 * Date: 2025-07-15
 * Time: 21:33
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle......");
        HttpSession session = request.getSession(false);
        if (!checkUser(session)){
            response.setContentType("text/html;charset=utf-8");
            String msg = "用户未登录";
            response.setStatus(401);
            response.getOutputStream().write(msg.getBytes("UTF-8"));
            return false;
        }
        return true;
    }

    public boolean checkUser(HttpSession session){
        if (session == null || session.getAttribute(StringConstant.SESSION_USER_KEY) == null){
            log.warn("用户未登录");
            return false;
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(StringConstant.SESSION_USER_KEY);
        if (userInfo == null){
            log.warn("用户未登录");
            return false;
        }
        log.info("用户已登录");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle......");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion......");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
